const multer = require('multer'); //文件上传模块
const mkdirp = require('mkdirp');
const config = require('../config');
const dateformat = require('dateformat'); //时间格式化
const path = require('path');
const md5 = require('md5')
const fs = require('fs');

var tools = {
    multer() {
        var storage = multer.diskStorage({
            //配置上传的目录
            destination: async function(req, file, cb) {

                let day = dateformat(new Date(), 'yyyymmdd'); //20201112
                let dir = path.join(config.uploadFile, day); // public/uploads/20201112
                await mkdirp(dir);

                cb(null, dir) //上传之前目录必须存在
            },
            //修改上传的文件名
            filename: function(req, file, cb) {
                // 1.获取文件后缀
                let extname = path.extname(file.originalname);
                // 2.根据时间戳生成文件名
                cb(null, Date.now() + extname);
            }
        })

        var upload = multer({ storage: storage });
        return upload;

    },

    //文件删除模块  例：  filePath = "/uploads/20201112/1605271941038.jpg";
    delFile(filePath) {
        return new Promise((resolve, reject) => {
            fs.exists(path.join(__dirname, "public", filePath), function(exists) {
                // console.log(exists ? "创建成功" : "创建失败");
                console.log(exists); // 文件有 true  没有false
                //文件有就删除
                if (exists) {
                    fs.unlinkSync(path.join(__dirname, filePath));
                    console.log("删除成功");
                    resolve(true)
                } else {
                    console.log("删除失败");
                    reject(false)
                }
            })
        });
    },

    //生成商品id
    /** 
     * 生成唯一字符串  不加前缀 默认是 32个字符
     * @param {[String]}   unique  [变量名,可选] 使数据更具唯一性
     * @param {[String]}   prefix  [变量名,可选] 使数据更具唯一性
     */
    encryption(unique, prefix) {
        return new Promise((resolve, reject) => {
            prefix = prefix || '';
            var str = prefix + md5(prefix + String(Math.random()) + String(Date.now()) + unique)
            resolve(str);
        });
    },

    //分页模块 要展示的页码
    /**
     * 分页功能模块
     * 参数：当前页码，页码显示数，页码总数
     */
    layPage(current, showCnt, pageCnt) {
        var array = []
        for (var i = 0; i < pageCnt; i++) {
            array.push(i + 1)
        }
        if (pageCnt <= showCnt) {
            return array.splice(0, pageCnt)
        } else if (pageCnt - current < showCnt - 1) {
            // 避免这种现象(12, 4, 15)
            return array.splice(pageCnt - showCnt, showCnt)
        } else if (current - Math.ceil(showCnt / 2) >= 0) {
            return array.splice(current - Math.ceil(showCnt / 2), showCnt)
        } else {
            return array.splice(0, showCnt)
        }
    }
}

module.exports = tools;